// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.cli;

import static java.lang.System.out;

import java.io.IOException;

import net.web2me.api.Parsable;
import net.web2me.api.ParserExecutor;
import net.web2me.api.ParserFactory;
import net.web2me.util.FileUtil;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * A CLI client
 * 
 * @author web2me
 * 
 */
public class Web2MeCli {
	
	private static Logger logger = Logger.getLogger(Web2MeCli.class);
	
	private static String url;
	
	private static String dir;
	
	private static String parserName;

	/**
	 * @param args
	 *            This method expects 3 arguments: url, destiny directory and
	 *            parser name
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		if ((System.getProperty("debug") != null && Boolean.valueOf(System
				.getProperty("debug")))) {
			PropertyConfigurator.configure(Web2MeCli.class
					.getResource("/log4j-debug.properties"));
		}

		if (checkParameters(args)) {
			try {
				logger.info("Processing: " + url);
				
				ParserExecutor executor = new ParserExecutor(
						parserName,
						dir,
						url,
						CliParams.isSet("history"),
						CliParams.isSet("metadata")
						);
				
				String time = executor.execute();

				logger.info("The process has finished");

				processFinished(time);
			} catch (Exception e) {
				logger.error("An error ocurred while executing:");
				logger.error(e);
			}
		}
	}

	private static void processFinished(String time) {
		logger.info("Site Downloader status");
		logger.info("**********************");
		logger.info("Total execution time: " + time);
	}

	/**
	 * Checks that the parameters has been correctly passed to the program.<br>
	 * The supported parameters are:
	 * <ul>
	 * <li><b>-u</b> or <b>--url</b>: The URL of the site that is going to be
	 * parsed
	 * <li><b>-d</b> or <b>--directory</b>: The directory where the content of
	 * the site is going to be downloaded
	 * <li><b>-p</b> or <b>--parser</b>: The parser that id that can handle the
	 * site
	 * <li><b>-h</b> or <b>--help</b>: Displays the help menu
	 * </ul>
	 * 
	 * @param params
	 * @return true if the parameters are ok, or false if they are wrong or the
	 *         user used <code>-h</code> or <code>--help</code>
	 * @throws IOException 
	 */
	private static boolean checkParameters(String[] params) throws IOException {
		if (params == null) {
			return false;
		}
		
		if (params.length == 0) {
			return false;
		}

		for (int i = 0; i < params.length; i++) {
			if (params[i].equals("-u") || params[i].equals("--url")) {
				url = params[++i];
			} else if (params[i].equals("-d")
					|| params[i].equals("--directory")) {
				dir = params[++i];
			} else if (params[i].equals("-p") || params[i].equals("--parser")) {
				parserName = params[++i];
			} else if (params[i].equals("-h") || params[i].equals("--help")) {
				showHelp();
				return false;
			} else if (params[i].equals("-l")
					|| params[i].equals("--parsers-list")) {
				showParsersList();
				return false;
			}
		}

		return true;
	}

	private static void showParsersList() {
		Parsable parsers[] = ParserFactory.getAllParsers();

		out.println(" ");
		out.println("Web2Me parsers list:");
		out.println("----------------------");
		out.println(" ");

		for (Parsable parser : parsers) {
			out.print(parser.getClass().getSimpleName());
			out.print("\t");
			out.print(parser.getDescription());
			out.print("\n");
		}

		out.println(" ");
	}

	private static void showHelp() throws IOException {
		out.print(FileUtil.getContents(Web2MeCli.class.getResource("/cli_usage").openStream()));
	}
	
}